import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Form, Input, Modal, Checkbox, Button, Upload, Row, Col } from 'antd';
import PateoTable from '@/components/common/PateoTable';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import FileModal from './fileModal'
import { FolderOpenOutlined,  } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import { getToken } from '@/utils/utils';
import { getMd5 } from '@/utils/utils';
import { getOptAuthHeaders } from '@/utils/common';
import { fingerprintFetch } from '@/utils/request'

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  knowledgeBreakdown: state.knowledgeBreakdown,
  loading: state.loading.effects['http/getFetchPage'],
});

class CaseViewModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  constructor(props: any) {
    super(props);
    this.state = {
      fileVisible: false,
      viewFileInfo: {},
      viewHeight: 100,
      formValues: {},
      uploadFileInfo: {},
      list: [],
      pagination: {},
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, record, dispatch } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      //  查询案例列表
      //  /mscontent/knowledge/fault/case/save
      dispatch({
        type: 'http/getFetchPage',
        payload: { 
          url: '/mscontent/knowledge/fault/case/list',
          faultCode: record.faultCode,
          majorCode: record.majorCode,
        },
        callback: (res: any) => {
          if (res.statusCode === '0') {
            this.setState({
              list: res.data.list || [],
              pagination: res.data.pagination || {}
            })
          }
        }
      })
    }
  }

  beforeUpload = (file: any) => {
    const { name } = file;
    const list = name.split('.');
    const len = list.length;
    //  .docx, .xlsx, .pptx, .pdf
    //  .docx, .doc, .xlsx, .xls, .pptx, .ppt, .pdf
    if (len > 0 && ['docx', 'xlsx', 'pptx', 'pdf', 'doc', 'xls', 'ppt'].indexOf(list[len-1]) !== -1) {
      return true;
    } else {
      message.warning('请选择.docx，.doc，.xlsx，.xls，.pptx，.ppt，.pdf类型的文件');
      return false;
    }
  }

  onChange = (info: any) => {
    if (info.file.status === 'done' && info.file.response && info.file.response.responseCode == 200) {
      message.success('上传成功');
      this.setState({
        uploadFileInfo: info.file.response.fileRecordList[0] || {},
      }, () => {
        this.formRef.current?.setFieldsValue({
          file: info.file.response.fileRecordList[0].originalFileName || '',
        })
      })
    } else if (info.file.status === 'error') {
      message.error('上传失败');
    }
  }

  //  关闭操作
  cancel = () => {
    const { closeModal } = this.props;
    closeModal();
    this.setState({
      viewFileInfo: {},
      viewHeight: 100,
      formValues: {},
      uploadFileInfo: {},
      list: [],
      pagination: {},
    })
    this.formRef.current?.resetFields();
  };

  //  查看
  handleView = (record: any) => {
    //  当前视口高
    const viewHeight = document.documentElement.scrollHeight - 100;
    this.setState({
      fileVisible: true,
      viewFileInfo: record,
      viewHeight: viewHeight > 100 ? viewHeight : 100
    })
  }

  //  下载
  handleDownload = (record: any) => {
    const { fileName, fileUrl } = record;
    if (!fileUrl) {
      message.error('日志文件缺失或格式不正确，无法下载！');
      return;
    }
    const str = `${window.g.url}/common/download?strUrl=` + fileUrl;
    const tempStr = decodeURIComponent(fileUrl);
    let md5 = getMd5('strUrl=' + tempStr);

    const newOptions: any = {};
    newOptions.method = 'GET';
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      shaSign: md5,
      'Content-Type': 'application/json;charset=utf-8',
    };
    fingerprintFetch(str, newOptions)
      .then(response => {
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display = 'none';
        aLink.href = window.URL.createObjectURL(blob);
        aLink.download = fileName;
        aLink.click();
        document.body.removeChild(aLink);
      })
      .catch(() => message.error('下载失败，请稍后在试!'));
  }

  //  删除
  handleDel = (record: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'http/delData',
      payload: { 
        url: `/mscontent/knowledge/fault/case/delete?id=${record.id}`,
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          message.success('删除成功');
          this.refreshPage();
        }
      }
    });
  }

  closeFileModal = () => {
    this.setState({
      fileVisible: false,
      viewFileInfo: {}
    })
  }

  ok = (vals: any) => {
    const { dispatch, record } = this.props;
    if ( !vals.file ) {
      message.warning('请选择文件');
      return;
    };
    const { uploadFileInfo: { fileName, fileUri, suffix, originalFileName } } = this.state;
    dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: '/mscontent/knowledge/fault/case/save',
        majorCode: record.majorCode,
        faultCode: record.faultCode,
        fileName: originalFileName,
        fileUrl: fileUri,
        fileExt: suffix,
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          message.success('操作成功');
          this.refreshPage();
          this.formRef.current?.setFieldsValue({ file: '', });
        }
      }
    })
  }

  //  刷新列表数据
  refreshPage = () => {
    const { dispatch, record } = this.props;
    dispatch({
      type: 'http/getFetchPage',
      payload: { 
        url: '/mscontent/knowledge/fault/case/list',
        faultCode: record.faultCode,
        majorCode: record.majorCode,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            list: res.data.list || [],
            pagination: res.data.pagination || {}
          })
        }
      }
    })
  }

  render() {
    const { dispatch, modalVisible, pathname, record, loading } = this.props;
    const { formValues, fileVisible, viewFileInfo, viewHeight, list, pagination } = this.state;

    const page = {
      current: pagination?.current || 1,
      pageSize: pagination?.pageSize || 1,
      total: pagination.total || 0,
    }

    const columns = [
      {
        title: '文件名称',
        dataIndex: 'fileName',
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 240,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '查看',
              key: 'view',
              auth: 'knowledgeBreakdown_show',
              onConfirm: () => this.handleView(record),
            },
            {
              title: '下载',
              key: 'download',
              auth: 'knowledgeBreakdown_show',
              onConfirm: () => this.handleDownload(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'knowledgeBreakdown_show',
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDel(record),
            },
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        }
      }
    ]

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => (
        <span>共&nbsp;{page === undefined ? 0 : page.total}&nbsp;条</span>
      ),
    };

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (r: any) => r.id,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
      onChange: (pagination: any, filters: any, sorter: any, extra: any) => {
        const { current, pageSize } = pagination;
        //  查询案例列表
        dispatch({
          type: 'http/getFetchPage',
          payload: { 
            url: '/mscontent/knowledge/fault/case/list',
            faultCode: record.faultCode,
            majorCode: record.majorCode,
            current,
            pageSize,
          },
          callback: (res: any) => {
            if (res.statusCode === '0') {
              this.setState({
                list: res.data.list || [],
                pagination: res.data.pagination || {}
              })
            }
          }
        })
      }
    };
    
    const footer = (
      <div>
        <Button size="small" onClick={this.cancel}>
          关闭
        </Button>
      </div>
    );

    const formItemLayout = {
      labelCol: {
        xs: { span: 0 },
        sm: { span: 0 },
      },
      wrapperCol: {
        xs: { span: 16 },
        sm: { span: 16 },
      },
    };

    const domain = window.g.url;
    // const fileurl = '/common/upload/all';
    const fileurl = '/upload/single?bizType=knowledge';
    const filestr = `${domain}${fileurl}`;
    const md5 = getMd5('bizType=knowledge');

    const prefixSelector = (
      <Form.Item noStyle>
        <Upload
          action={filestr}
          headers={{
            OptAuthorization: `${getToken()}`,
            ...getOptAuthHeaders(),
            shaSign: md5,
          }}
          beforeUpload={this.beforeUpload}
          onChange={this.onChange}
          maxCount={1}
          multiple={false}
          showUploadList={false}
          accept=".docx, .doc, .xlsx, .xls, .pptx, .ppt, .pdf"
        >
          <Button icon={<FolderOpenOutlined />}>选择文件</Button>
        </Upload>
      </Form.Item>
    );

    return (
      <Modal
        style={{ top: 20 }}
        footer={footer}
        width={700}
        // bodyStyle={{ height: '700px' }}
        title="案例文件"
        visible={modalVisible}
        onCancel={this.cancel}
      >
        <div style={{ position: 'relative' }}>
          <Form
            {...formItemLayout}
            style={{ marginTop: 12 }}
            ref={this.formRef}
            onFinish={this.ok}
          >
            <Form.Item
              name="file"
              colon={false}
              label=" "
              rules={[]}
            >
              <Input disabled addonBefore={prefixSelector} style={{ width: '100%' }} />
            </Form.Item>
          </Form>
          <Button type="primary" style={{ position: 'absolute', right: '100px', top: '-1px' }} onClick={() => {
            this.formRef?.current?.submit();
          }}>上传文件</Button>
        </div>
        <PateoTable
          extraHandle={true}
          tableProps={tableProps}
          fetchParams={{ type: 'http/getFetchPage', url: '/mscontent/knowledge/fault/case/list' }}
          formValues={formValues}
        />
        <FileModal
          onRef={(modalRef: any) => (this.fileModal = modalRef)}
          modalVisible={fileVisible}
          file={viewFileInfo}
          pathname={pathname}
          width={'100%'}
          height={viewHeight}
          closeModal={this.closeFileModal}
        />
      </Modal>
    )
  }
}
export default connect(mapStateToProps)(CaseViewModal);
